package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class RegisterDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入姓名：");
        String userName = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        System.out.println("请输入昵称：");
        String nickName = sc.nextLine();
        System.out.println("请输入年龄：");
        int age = sc.nextInt();
        try (Connection connection = DButil.getConnection()) {
            Statement statement = connection.createStatement();
            String sqlUName = "SELECT username FROM user WHERE username = '" + userName + "'";
            ResultSet rs = statement.executeQuery(sqlUName);
            if (rs.next()) {
                System.out.println("用户名已存在，注册失败！！！");
            } else {
                String sql = "INSERT INTO user(username, password, nickname, age) " +
                        "VALUES ('" +
                        userName + "','" +
                        password + "','" +
                        nickName + "'," +
                        age + ");";
                int num = statement.executeUpdate(sql);
                System.out.println(num > 0 ? "注册成功" : "注册失败");
            }
            sc.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
